<template>
  <view class="download-container">
    <button @click="downloadNetworkImage" type="primary">下载网络图片</button>
    <image :src="downloadedImageUrl" mode="widthFix" style="width: 100%; margin-top: 20rpx;" v-if="downloadedImageUrl" />
    <view class="progress" v-if="progress > 0 && progress < 100">
      下载进度：{{ progress }}%
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      downloadedImageUrl: '', // 下载后图片路径
      progress: 0 // 下载进度
    };
  },
  methods: {
    downloadNetworkImage() {
      const imageUrl = 'https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg';
      
      // 下载网络图片
      const downloadTask = uni.downloadFile({
        url: imageUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            this.downloadedImageUrl = res.tempFilePath; // 显示下载后的图片
            console.log('图片下载成功，临时路径：', res.tempFilePath);
            
            // 预览下载的图片
            uni.previewImage({
              urls: [res.tempFilePath]
            });
          }
        },
        fail: (err) => {
          console.error('图片下载失败：', err);
        },
        complete: () => {
          this.progress = 0; // 重置进度
        }
      });
      
      // 监听下载进度
      downloadTask.onProgressUpdate((res) => {
        this.progress = res.progress;
        console.log(`下载进度：${res.progress}%`);
        console.log(`已下载字节：${res.totalBytesWritten}`);
        console.log(`总字节数：${res.totalBytesExpectedToWrite}`);
      });
    }
  }
};
</script>

<style scoped>
.download-container {
  padding: 20rpx;
}
.progress {
  margin-top: 10rpx;
  font-size: 26rpx;
  color: #007AFF;
}
</style>